package com.sec.etech.presale.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sec.etech.common.fanutil.FanUtil;
import com.sec.etech.common.service.Mail;
import com.sec.etech.common.util.RequestHolder;
import com.sec.etech.form.cust.util.FormDefDataUtil;
import com.sec.etech.org.service.EtechUserService;
import com.sec.etech.org.service.EtechUserUtil;
import com.sec.etech.presale.mapper.PrePorjectMapper;
import com.sec.etech.presale.model.PreProject;
import org.apache.commons.collections4.MapUtils;
import org.openbpm.base.api.constant.BaseStatusCode;
import org.openbpm.base.api.response.impl.ResultMsg;
import org.openbpm.base.core.util.StringUtil;
import org.openbpm.bus.model.BusinessData;
import org.openbpm.form.model.FormDefData;
import org.openbpm.form.service.FormDefDataService;
import org.openbpm.sys.util.ContextUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class PrePorjectService extends ServiceImpl<PrePorjectMapper, PreProject> {

    @Autowired
    EtechUserService etechUserService;
    @Autowired
    FormDefDataService formDefDataService;
    @Resource
    JdbcTemplate jdbcTemplate;
    @Autowired
    PreProjectHelper preProjectHelper;

    //添加子项目
    public ResultMsg<Boolean> addSubProject(String npdfs1id) throws Exception {
        ResultMsg<Boolean> result = new ResultMsg(BaseStatusCode.SYSTEM_ERROR, "添加子项目失败");
        if (StrUtil.isNotBlank(npdfs1id)) {
            String key = "preProjectDetail";
            FormDefData formDefData = this.formDefDataService.getByFormDefKey(key, npdfs1id, false);
            if (formDefData != null) {
                ResultMsg<JSONObject> resultMsg = this.copyPrjectById(npdfs1id);
                if (resultMsg.getIsOk()) {
                    JSONObject data = resultMsg.getData();
                    if (data != null) {
                        // 检查公用更新字段
                        for (String key1 : data.keySet()) {
                            JSONObject itemJson = data.getJSONObject(key1);
                            FormDefDataUtil.checkCommonUpdateDate(itemJson);
                            data.put(key1, itemJson);
                        }
                    }
                    JSONObject jsonObject = this.formDefDataService.saveFormDefData(data, key, false);
                    Map<String, Object> pre_project_detail = jsonObject.getObject("pre_project_detail", BusinessData.class).getData();
                    this.sendAddemail(new JSONObject(pre_project_detail));
                    return new ResultMsg(true);
                } else {
                    result = new ResultMsg(BaseStatusCode.SYSTEM_ERROR, resultMsg.getMsg());
                }
            }
        }
        return result;
    }

    /**
     * 复制项目对象
     *
     * @param npdfs1id
     * @return
     */
    public ResultMsg<JSONObject> copyPrjectById(String npdfs1id) throws Exception {
        String sql = "select * from {} where npdfs1id=" + npdfs1id;
        //售前项目基本信息
        List<Map<String, Object>> list = jdbcTemplate.queryForList(StrUtil.format(sql, "pre_project_basicinfo"));
        if (CollectionUtil.isNotEmpty(list)) {
            //id清空，num加下划线01 如果01已存在就是02以此类推，时间人员重置
            Map<String, Object> map = list.get(0);
            if (map.get("opportunity") != null || map.get("num").toString().split("_").length >= 3) {
                //如果不为空代为这个项目是子项目，子项目不能再增加子项目,length >=3 为了兼容老数据
                ResultMsg<JSONObject> resultMsg = new ResultMsg();
                resultMsg.setOk(Boolean.FALSE);
                resultMsg.setCode(BaseStatusCode.SYSTEM_ERROR.getCode());
                resultMsg.setMsg("子项目不能添加子项目");
                return resultMsg;
            }
            map.put("npdfs1id", null);
            String num = map.get("num").toString();
            List<String> results = jdbcTemplate.queryForList(StrUtil.format("select REPLACE(num,'{}_','') AS num from pre_project_basicinfo where num like '{}_%' order by num desc limit 1", num, num), String.class);
            if (CollectionUtil.isNotEmpty(results)) {
                String strNum = results.get(0);
                map.put("num", num + "_" + (Integer.parseInt(strNum) + 1 < 10 ? "0" : "") + (Integer.parseInt(strNum) + 1));
            } else {
                map.put("num", num + "_01");
            }
            String currentUserId = ContextUtil.getCurrentUserId();
            Timestamp date = new Timestamp(new Date().getTime());
            map.put("postuid", currentUserId);
            map.put("postdate", date);
            map.put("lastuid", currentUserId);
            map.put("lastdate", date);
            // 增加项目机会字段
            map.put("opportunity", npdfs1id);

            //人员配置表
            List<Map<String, Object>> list2 = jdbcTemplate.queryForList(StrUtil.format(sql, "pre_project_users"));
            if (CollectionUtil.isNotEmpty(list2)) {
                Map<String, Object> map2 = list2.get(0);
                if (!currentUserId.equals(MapUtils.getString(map2, "salerAuid", ""))
                        && !currentUserId.equals(MapUtils.getString(map2, "salerBuid", ""))
                        && !preProjectHelper.hasRole("S1_register")
                        && !currentUserId.equals("417137619324108800")) {
                    //必须是项目经理  或者项目售前登记人（权限控制或者角色控制）
                    //才能添加子项目
                    ResultMsg<JSONObject> resultMsg = new ResultMsg();
                    resultMsg.setOk(Boolean.FALSE);
                    resultMsg.setCode(BaseStatusCode.SYSTEM_ERROR.getCode());
                    resultMsg.setMsg("必须是项目经理或者项目售前登记人才能添加子项目");
                    return resultMsg;
                }
                map2.put("npdfs1id", null);
                map2.put("postuid", currentUserId);
                map2.put("postdate", date);
                map2.put("lastuid", currentUserId);
                map2.put("lastdate", date);
                map.put("pre_project_users", map2);
            } else if (!preProjectHelper.hasRole("S1_register") && !currentUserId.equals("417137619324108800")) { //没有找到人员，判断是否是售前登记人角色
                ResultMsg<JSONObject> resultMsg = new ResultMsg();
                resultMsg.setOk(Boolean.FALSE);
                resultMsg.setCode(BaseStatusCode.SYSTEM_ERROR.getCode());
                resultMsg.setMsg("必须是项目经理或者项目售前登记人才能添加子项目");
                return resultMsg;
            }

            //售前热力信息
            List<Map<String, Object>> list1 = jdbcTemplate.queryForList(StrUtil.format(sql, "pre_project_heatinginfo"));
            if (CollectionUtil.isNotEmpty(list1)) {
                Map<String, Object> map1 = list1.get(0);
                map1.put("npdfs1id", null);
                map1.put("postuid", currentUserId);
                map1.put("postdate", date);
                map1.put("lastuid", currentUserId);
                map1.put("lastdate", date);
                map.put("pre_project_heatinginfo", map1);
            }

            JSONObject data = new JSONObject();
            data.put("pre_project_detail", JSONObject.parseObject(JSONUtils.toJSONString(map)));
            //todo 保存项目变动记录  admin admin 2020-07-23 10:04:52 新建子项目

            return new ResultMsg(data);

        }
        return null;
    }

    private String mailRowStringUtil(String label, Object value) {
        return "<tr><td style=`font-family:等线;color:#7f7f7f; font-weight:bold; text-align:right`>"
                + label + "：</td><td style=`font-family:等线`>" + ((value == null || "null".equals(value)) ? " " : value) + "</td></tr>";
    }
    /**
     * 售前技术归口为指定部门时才触发邮件
     */
    public void sendAddemail(JSONObject object) {
        List<Map<String, Object>> mapList = getBasicInfoBynpdfs1id(getStrValue(object.get("npdfs1id")));
        Map<String, Object> dataMap = mapList.get(0);
        //仅售前技术归口为以下指定部门时才触发邮件
        List<String> orderDepartmentList = Arrays.asList("【STP】设计处", "【STWC】设计处", "【STP】技术发展处", "【STP】工艺处");
        if (dataMap.get("orderdprtname") == null
                || StringUtil.isEmpty(String.valueOf(dataMap.get("orderdprtname")))
                || !orderDepartmentList.contains(dataMap.get("orderdprtname").toString().replace(" ", ""))) {
            return;
        }
        List<String> toUidList = new ArrayList<>();
        //条目创建者
        if (!"417137619324108800".equals(object.getString("postuid"))) {
            toUidList.add(object.getString("postuid"));
        }
        String toUidSql;
        String orderDepartment = dataMap.get("orderdprtname").toString().replace(" ", "");
        if ("【STP】设计处".equals(orderDepartment)) {
            //STP设计处,本体设计室,热力叶片室、技术服务室售前项目负责人
            toUidSql = "SELECT s1_manager FROM proj_plantask_z_designdprt WHERE designdprtid > 0 AND designdprtid in ('424605755300904961','8','6','431044062122606593')";
        } else if ("【STWC】设计处".equals(orderDepartment)) {
            //STWC技术处,部件设计室,热力系统室售前项目负责人
            // TODO >>G
            toUidSql = "SELECT s1_manager FROM proj_plantask_z_designdprt WHERE designdprtid > 0 AND designdprtid in ('422323834606583809','433059503092269057', '433059423042404353')";
        } else if ("【STP】技术发展处".equals(orderDepartment)) {
            //STP技术发展处售前项目负责人
            toUidSql = "SELECT s1_manager FROM proj_plantask_z_designdprt WHERE designdprtid > 0 AND designdprtid in ('424587255054336001')";
        } else {
            //工艺处售前项目负责人
            toUidSql = "SELECT s1_manager FROM proj_plantask_z_designdprt WHERE designdprtid > 0 AND designdprtid in ('423314484854259713')";
        }
        List<String> result = jdbcTemplate.queryForList(toUidSql, String.class).stream().filter(StringUtil::isNotEmpty).collect(Collectors.toList());
        for (String r : result) {
            toUidList.addAll(Arrays.asList(r.split(",")));
        }
        //去重
        toUidList = toUidList.stream().distinct().collect(Collectors.toList());
        //抄送平台管理员
        List<String> s1ManagerList = etechUserService.getUserIdsByRoleCode("S1_manager");
        String sql = "SELECT\n" +
                "\t* \n" +
                "FROM\n" +
                "\t`pre_project_customergroups` AS t0\n" +
                "\tLEFT JOIN proj_project_z_customergroup AS t1 ON t0.customergroupid = t1.customergroupid \n" +
                "WHERE\n" +
                "\tnpdfs1id = {}";
        List<Map<String, Object>> mapList2 = jdbcTemplate.queryForList(StrUtil.format(sql, object.get("npdfs1id")));
        List<String> list = FanUtil.mapListToList(mapList2, "customergroupfullname");
        if (toUidList != null && toUidList.size() > 0) {
            String name = "【售前项目】新增" + getStrValue(object.getString("num")) + " " + getStrValue(object.getString("projectname")) + " 通知";
            String content = "<div style=`font-size:16px;font-family:等线;mso-no-proof:yes`>" +
                    "您好：<br><br>" + "新增售前项目，信息如下：" +
                    "<div style=`margin-left:30px;`><table style=`font-size:16px;`>"
                    + mailRowStringUtil("创建人", EtechUserUtil.getUserNameById(object.getLong("postuid")))
                    + mailRowStringUtil("项目编号", dataMap.get("num"))
                    + mailRowStringUtil("项目名称", dataMap.get("projectname"))
                    + mailRowStringUtil("项目属性", dataMap.get("reformname"))
                    + mailRowStringUtil("产品规划", dataMap.get("schemename"))
                    + mailRowStringUtil("销售部门", dataMap.get("originname"))
                    + mailRowStringUtil("售前技术归口", dataMap.get("orderdprtname"))
                    + mailRowStringUtil("售前技术责任", dataMap.get("dutyname"))
                    + mailRowStringUtil("投资方", String.join("、", list))
                    + mailRowStringUtil("所属集团", dataMap.get("customergroupfullname"))
                    + mailRowStringUtil("设计院", dataMap.get("institutename"))
                    + mailRowStringUtil("业主(电厂)名称", dataMap.get("customername"))
                    + mailRowStringUtil("机组形式", dataMap.get("thermalperformname"))
                    + mailRowStringUtil("销售经理", dataMap.get("salesmanageruname"))
                    + mailRowStringUtil("机组台数(台)", dataMap.get("quantity"))
                    + mailRowStringUtil("机组容量(MW)", dataMap.get("capacity"))
                    + mailRowStringUtil("产品板块", dataMap.get("platename"))
                    + mailRowStringUtil("产品领域", dataMap.get("fieldname"))
                    + mailRowStringUtil("驱动对象", dataMap.get("driveobjectname"))
                    + mailRowStringUtil("供货范围", dataMap.get("supplyscopename"))
                    + mailRowStringUtil("项目国家", dataMap.get("country"))
                    + mailRowStringUtil("项目省份", dataMap.get("provincename"))
                    + mailRowStringUtil("项目市场", dataMap.get("marketname"))
                    + mailRowStringUtil("产品编号", dataMap.get("modelname"))
                    + mailRowStringUtil("联合循环布置方式", dataMap.get("cycletypename"))
                    + mailRowStringUtil("改造标的", dataMap.get("reformordersname"))
                    + mailRowStringUtil("项目备注", dataMap.get("projectremark"))
                    + "</table></div><br>"
                    + "&nbsp&nbsp <span style='background:yellow;mso-highlight:yellow'>请及时查阅（其他更详细信息请点击下方链接查看）</span><br>" +
                    "&nbsp&nbsp <a href='" + RequestHolder.getUrl() + "/form/formDef/vueFormDetail.html?key=preProjectDetail&id=" + object.getString("npdfs1id") + "' style=`text-decoration: none; color:#0070c0; font-weight:bold`>点击此处进入该售前项目详情页（注意使用谷歌浏览器查看）</a><br>" +
                    "&nbsp&nbsp <a href='" + RequestHolder.getUrl() + "/form/formCustSql/view/formCustSqlView.html?code=preProjectList' style=`text-decoration: none; color:#0070c0; font-weight:bold`>点击此处进入售前项目列表（注意使用谷歌浏览器查看）</a><br><br> " +
                    "&nbsp&nbsp<div style=`margin-top: 10px; color: red; font-size: 14px`>此邮件为平台自动发送，请勿回复！</div>"
                    + "</div>";
            new Mail(toUidList, name, content, null, false, s1ManagerList).SendEmail();
        }
    }

    public Long getLongValue(Long value) {
        if (value == null) {
            return 0L;
        }
        return value.longValue();
    }

    public String getStrValue(Object value) {
        if (value == null) {
            return "";
        }
        return String.valueOf(value);
    }

    public boolean ComparedLongValue(Long value1, Long value2) {
        return getLongValue(value1).equals(getLongValue(value2));
    }

    public List<Map<String, Object>> getBasicInfoBynpdfs1id(String npdfs1id) {
        String sql = "SELECT \n" +
                "a.*,\n" +
                "IFNULL(b.reformname,'') AS reformname,\n" +
                "IFNULL(c.schemename,'') AS schemename,\n" +
                "IFNULL(d.originname,'') AS originname,\n" +
                "IFNULL(e.orderdprtname,'') AS orderdprtname,\n" +
                "IFNULL(f.dutyname,'') AS dutyname,\n" +
                "IFNULL(g.customergroupfullname,'') AS customergroupfullname,\n" +
                "IFNULL(h.institutename,'') AS institutename,\n" +
                "IFNULL(i.thermalperformname,'') AS thermalperformname,\n" +
                "IFNULL(j.platename,'') AS platename,\n" +
                "IFNULL(j.fieldname,'') AS fieldname,\n" +
                "IFNULL(k.driveobjectname,'') AS driveobjectname,\n" +
                "IFNULL(l.supplyscopename,'') AS supplyscopename,\n" +
                "IFNULL(m.provincename,'') AS provincename,\n" +
                "IFNULL(n.marketname,'') AS marketname,\n" +
                "IFNULL(r.capacity,'') AS capacity,\n" +
                "concat(IFNULL(o.cycletypecode,''),' ',IFNULL(o.cycletypename,'')) AS cycletypename,\n" +
                "CONCAT(IFNULL(p.model,''),' ',IFNULL(p.types,'')) AS modelname,\n" +
                "IFNULL(q.customername,'') AS customername\n" +
                "FROM `pre_project_basicinfo` AS a\n" +
                "LEFT JOIN proj_project_z_reform AS b ON a.reformid = b.reformid\n" +
                "LEFT JOIN proj_project_z_scheme AS c ON a.schemeid = c.schemeid\n" +
                "LEFT JOIN proj_project_z_origin AS d ON a.originid = d.originid\n" +
                "LEFT JOIN proj_project_z_orderdprt AS e ON a.orderdprtid = e.orderdprtid\n" +
                "LEFT JOIN proj_project_z_duty AS f ON a.dutyid = f.dutyid\n" +
                "LEFT JOIN proj_project_z_customergroup AS g ON a.customergroupid = g.customergroupid\n" +
                "LEFT JOIN proj_project_z_institute AS h ON a.instituteid = h.instituteid\n" +
                "LEFT JOIN prod_model_z_thermalperform AS i ON a.thermalperformid = i.thermalperformid\n" +
                "LEFT JOIN proj_project_z_plate AS j ON a.plateid = j.plateid\n" +
                "LEFT JOIN proj_project_z_driveobject AS k ON a.driveobjectid = k.driveobjectid\n" +
                "LEFT JOIN proj_project_z_supplyscope AS l ON a.supplyscopeid = l.supplyscopeid\n" +
                "LEFT JOIN proj_project_z_province AS m ON a.provinceid = m.provinceid\n" +
                "LEFT JOIN proj_project_z_market AS n ON a.marketid = n.marketid\n" +
                "LEFT JOIN prod_model_z_cycle_type AS o ON a.cycletypeid = o.cycletypeid\n" +
                "LEFT JOIN prod_model AS p ON a.modelid = p.modelid\n" +
                "LEFT JOIN proj_customer AS q ON a.customerid = q.customerid " +
                "LEFT JOIN pre_project_heatinginfo AS r ON a.npdfs1id = r.npdfs1id " +
                " WHERE a.npdfs1id = {}";
        return jdbcTemplate.queryForList(StrUtil.format(sql, npdfs1id));
    }
}
